package cn.com.homeyoda.aimate.aihealth.base;


import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.MaterialDialog;
import com.wzq.mvvmsmart.base.BaseFragmentMVVM;
import com.wzq.mvvmsmart.utils.KLog;

import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.manager.LoginStateManager;
import cn.com.homeyoda.aimate.aihealth.ui.login.LoginActivity;
import cn.com.homeyoda.aimate.aihealth.utils.LoadingStateManager;
import cn.com.homeyoda.aimate.aihealth.utils.MaterialDialogUtils;
import cn.com.homeyoda.aimate.aihealth.utils.ShowLoadingUtil;

public abstract class BaseFragment<V extends ViewDataBinding, VM extends BaseViewModel> extends BaseFragmentMVVM<V, VM> {
    public final String TAG = getClass().getSimpleName();
    private MaterialDialog dialog;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        observeLoadingState();
    }

    protected void doLogin(String userId) {
        LoginStateManager.getInstance().login(userId);
    }

    protected void doLogout() {
        LoginStateManager.getInstance().logout();
    }

    protected void startLoginActivity() {
        LoginActivity.start(requireActivity());
    }

    protected boolean isLogin() {
        return LoginStateManager.getInstance().isLogin();
    }

    public void showLoading(String title) {
        if (dialog != null) {
            dialog = dialog.getBuilder().title(title).build();
            dialog.show();
        } else {
            MaterialDialog.Builder builder = MaterialDialogUtils.showIndeterminateProgressDialog(getActivity(), title, true);
            dialog = builder.show();
        }
    }

    public void dismissLoading() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void observeLoadingState() {
        LoadingStateManager.getInstance().getLoadingState()
                .observe(this, isLoading -> {
                    Log.i("huadi","isLoading====BaseFragment===="+isLoading);
                    if (isLoading) {
                        showLoadingDialog();
                    } else {
                        hideLoadingDialog();
                    }
                });
    }

    protected void showLoadingDialog() {
        // 实现你的加载对话框显示逻辑
        ShowLoadingUtil.showLoading(getActivity());
    }

    protected void hideLoadingDialog() {
        // 实现你的加载对话框隐藏逻辑
        ShowLoadingUtil.dismiss();
    }

}
